/**
 * 个人中心页面
 * 展示用户信息和各种功能入口
 */
import React, { useEffect } from 'react';
import {
  ScrollView,
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Image,
} from 'react-native';
import SafeTabBarWrapper from '../components/SafeTabBarWrapper';
import Icon from 'react-native-vector-icons/Ionicons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { useUser } from '../context/UserContext';
import { ToastManager } from '../components/Toast';
import {
  COLORS,
  RADIUS,
  FONT_SIZE,
  FONT_WEIGHT,
  SPACING,
  SHADOWS,
} from '../styles/constants';

// 菜单项配置
const menuItems = [
  {
    id: 'settings',
    icon: 'settings-outline',
    label: '设置',
    route: 'Settings',
  },
  {
    id: 'account',
    icon: 'person-circle-outline',
    label: '账号与安全',
    route: 'AccountSecurity',
  },
  {
    id: 'feedback',
    icon: 'chatbubble-ellipses-outline',
    label: '意见反馈',
    route: 'Feedback',
  },
  {
    id: 'about',
    icon: 'information-circle-outline',
    label: '关于我们',
    route: 'About',
  },
];

export default function ProfileScreen() {
  const insets = useSafeAreaInsets();
  const topSpacing = Math.max(insets.top, 16);
  const navigation = useNavigation();
  const { user, isLoggedIn, logout } = useUser();

  useEffect(() => {
    // 用户状态已加载
  }, [isLoggedIn, user]);

  /**
   * 处理菜单项点击
   * @param {string} routeId - 路由ID
   */
  const handleMenuPress = routeId => {
    navigation.navigate(routeId);
  };

  const renderMenuItem = (item, index) => {
    const disabled =
      !isLoggedIn && item.route !== 'About' && item.route !== 'Settings';
    return (
      <TouchableOpacity
        key={item.id}
        style={[
          styles.menuItem,
          index !== menuItems.length - 1 && styles.menuItemDivider,
          disabled && styles.menuItemDisabled,
        ]}
        onPress={() => {
          if (disabled) {
            ToastManager.info('请先登录使用该功能');
            return;
          }
          handleMenuPress(item.route);
        }}
        activeOpacity={0.7}
      >
        <View style={styles.menuIconWrapper}>
          <Icon
            name={item.icon}
            size={20}
            color={disabled ? COLORS.text.light : COLORS.primary}
          />
        </View>
        <Text style={[styles.menuLabel, disabled && styles.menuLabelDisabled]}>
          {item.label}
        </Text>
        <Icon
          name="chevron-forward"
          size={18}
          color={disabled ? COLORS.border.dark : COLORS.text.light}
        />
      </TouchableOpacity>
    );
  };

  /**
   * 跳转到登录页面
   */
  const handleLoginPress = () => {
    navigation.navigate('Login');
  };

  /**
   * 显示退出登录确认对话框
   */
  const handleLogoutPress = async () => {
    try {
      await logout();
      ToastManager.success('已退出登录');
    } catch {
      ToastManager.error('退出登录失败');
    }
  };

  /**
   * 跳转到编辑资料页面
   */
  const handleEditProfile = () => {
    if (!isLoggedIn) {
      handleLoginPress();
      return;
    }
    navigation.navigate('EditProfile');
  };

  return (
    <SafeTabBarWrapper style={{ backgroundColor: COLORS.background.secondary }}>
      <ScrollView
        style={styles.container}
        contentContainerStyle={[
          styles.scrollContent,
          { paddingTop: topSpacing },
        ]}
        showsVerticalScrollIndicator={false}
      >
        <TouchableOpacity
          style={styles.headerCard}
          onPress={handleEditProfile}
          activeOpacity={0.8}
        >
          <View style={styles.avatarWrapper}>
            <Image
              source={{
                uri:
                  isLoggedIn && user?.avatar
                    ? user.avatar
                    : 'https://images.unsplash.com/photo-1544723795-3fb6469f5b39?w=200',
              }}
              style={styles.avatar}
            />
            {isLoggedIn && (
              <View style={styles.editAvatar}>
                <Icon name="camera-outline" size={16} color="#fff" />
              </View>
            )}
          </View>
          <View style={styles.userInfo}>
            <Text style={styles.userName}>
              {isLoggedIn
                ? user?.nickname || user?.tel || user?.phone || '旅行者'
                : '未登录游客'}
            </Text>
            {!isLoggedIn ? (
              <View style={styles.loginButton}>
                <Text style={styles.loginButtonText}>立即登录</Text>
                <Icon name="chevron-forward" size={16} color="#fff" />
              </View>
            ) : (
              <View>
                <Text style={styles.userDesc}>
                  {user?.remark || '探索更多美好旅程'}
                </Text>
                {user?.tel && (
                  <Text style={styles.userPhone}>📱 {user.tel}</Text>
                )}
              </View>
            )}
          </View>
          {isLoggedIn && (
            <Icon
              name="chevron-forward"
              size={20}
              color={COLORS.text.light}
              style={styles.arrowIcon}
            />
          )}
        </TouchableOpacity>
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>账号管理</Text>
          <View style={styles.card}>
            {menuItems.map((item, index) => renderMenuItem(item, index))}
          </View>
        </View>

        {isLoggedIn && (
          <TouchableOpacity
            style={styles.logoutButton}
            onPress={handleLogoutPress}
          >
            <Text style={styles.logoutText}>退出登录</Text>
          </TouchableOpacity>
        )}
      </ScrollView>
    </SafeTabBarWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.secondary,
  },
  scrollContent: {
    paddingBottom: SPACING.xxl,
  },
  headerCard: {
    margin: SPACING.lg,
    padding: SPACING.xl,
    borderRadius: RADIUS.xl,
    backgroundColor: COLORS.background.card,
    flexDirection: 'row',
    alignItems: 'center',
    ...SHADOWS.lg,
  },
  avatarWrapper: {
    marginRight: SPACING.lg,
  },
  avatar: {
    width: 70,
    height: 70,
    borderRadius: 35,
  },
  editAvatar: {
    position: 'absolute',
    bottom: 0,
    right: 0,
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: COLORS.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  userInfo: {
    flex: 1,
    marginRight: SPACING.sm,
  },
  arrowIcon: {
    marginLeft: SPACING.xs,
  },
  userName: {
    fontSize: FONT_SIZE.xl,
    fontWeight: FONT_WEIGHT.bold,
    color: COLORS.text.primary,
  },
  loginButton: {
    marginTop: SPACING.sm,
    backgroundColor: COLORS.primary,
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'flex-start',
    borderRadius: RADIUS.xl,
    paddingHorizontal: 14,
    paddingVertical: 6,
  },
  loginButtonText: {
    color: COLORS.white,
    fontWeight: FONT_WEIGHT.semibold,
    marginRight: SPACING.xs,
  },
  userDesc: {
    fontSize: FONT_SIZE.md,
    color: COLORS.text.disabled,
    marginTop: SPACING.xs,
  },
  userPhone: {
    fontSize: FONT_SIZE.sm,
    color: COLORS.text.quaternary,
    marginTop: SPACING.xs,
  },
  section: {
    marginHorizontal: SPACING.lg,
    marginTop: SPACING.md,
  },
  sectionTitle: {
    fontSize: FONT_SIZE.md,
    fontWeight: FONT_WEIGHT.semibold,
    color: COLORS.text.quaternary,
    marginBottom: SPACING.sm,
  },
  card: {
    backgroundColor: COLORS.background.card,
    borderRadius: RADIUS.lg,
    paddingHorizontal: SPACING.lg,
    borderWidth: StyleSheet.hairlineWidth,
    borderColor: COLORS.border.light,
  },
  menuItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 14,
  },
  menuItemDisabled: {
    opacity: 0.6,
  },
  menuItemDivider: {
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: COLORS.border.light,
  },
  menuIconWrapper: {
    width: 32,
    height: 32,
    borderRadius: RADIUS.lg,
    backgroundColor: COLORS.primaryLight,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: SPACING.md,
  },
  menuLabel: {
    flex: 1,
    fontSize: FONT_SIZE.lg,
    color: COLORS.text.secondary,
  },
  menuLabelDisabled: {
    color: COLORS.text.placeholder,
  },
  logoutButton: {
    marginHorizontal: SPACING.lg,
    marginTop: SPACING.xxl,
    paddingVertical: 14,
    borderRadius: 30,
    backgroundColor: COLORS.background.card,
    alignItems: 'center',
    justifyContent: 'center',
    ...SHADOWS.sm,
  },
  logoutText: {
    fontSize: FONT_SIZE.lg,
    fontWeight: FONT_WEIGHT.semibold,
    color: COLORS.primary,
  },
});
